<template>
  <div class="health-log-container">
    <div class="page-header">
      <h2>体检日志</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-select v-model="queryParams.userId" filterable  placeholder="请选择老人姓名" style="width: 100px" clearable>
            <el-option v-for="item in userList" :label="item.userName" :value="item.id" :key="item.id" >

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="openDialog()">
            <el-icon><Plus /></el-icon>添加记录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <el-table :data="healthLogList" border stripe v-loading="loading">
        <el-table-column prop="checkDate" label="记录日期" width="120" />
        <el-table-column prop="userName" label="姓名" width="120" />
        <el-table-column prop="bloodPressureSystolic" label="收缩压(mmHg)" width="120" />
        <el-table-column prop="bloodPressureDiastolic" label="舒张压(mmHg)" width="120" />
        <el-table-column prop="bloodSugar" label="血糖(mmol/L)" width="120" />
        <el-table-column prop="weight" label="体重(kg)" width="100" />
        <el-table-column prop="height" label="身高(cm)" width="100" />
        <el-table-column prop="otherDiseases" label="其他疾病史" min-width="200" show-overflow-tooltip />、
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="被记录人" prop="userId">
          <el-select :disabled="oneSelf" v-model="form.userId" placeholder="请选择老人姓名" style="width: 100%">
            <el-option v-for="item in userList" :label="item.userName" :value="item.id" :key="item.id" >

            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="记录日期" prop="checkDate">
          <el-date-picker
            v-model="form.checkDate"
            disabled
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收缩压" prop="bloodPressureSystolic">
              <el-input-number v-model="form.bloodPressureSystolic" :precision="0" :step="1" :min="70" :max="200" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="舒张压" prop="bloodPressureDiastolic">
              <el-input-number v-model="form.bloodPressureDiastolic" :precision="0" :step="1" :min="40" :max="120" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="血糖" prop="bloodSugar">
          <el-input-number v-model="form.bloodSugar" :precision="0" :step="1" :min="40" :max="200" style="width: 100%" />
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight">
          <el-input-number v-model="form.weight" :precision="1" :step="0.1" :min="20" :max="200" style="width: 100%" />
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="form.height" :precision="1" :step="0.1" :min="0" :max="300" style="width: 100%" />
        </el-form-item>
        <el-form-item label="其他疾病史" prop="otherDiseases">
          <el-input
              v-model="form.otherDiseases"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { get, post, put, del } from '@/utils/request'
import {getUserListByType} from "@/api/user.ts";
import type { FormInstance } from 'element-plus'
import type { HealthLog } from '@/types/health-log'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  startDate: '',
  endDate: '',
  userId:null
})

// 日期范围
const dateRange = ref<string[]>([])

// 数据列表
const healthLogList = ref<HealthLog[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => form.id ? '编辑体检日志' : '添加体检日志')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const userList= ref([])

// 表单对象
const form = reactive<HealthLog>({
  id: null,
  userId: null,
  checkDate: new Date().toISOString().split('T')[0],
  bloodPressureSystolic: 0.0,
  bloodPressureDiastolic: 0.0,
  bloodSugar: 0.0,
  weight: 60,
  height: 150,
  otherDiseases: '',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  userId: [{ required: true, message: '请选择被记录人', trigger: 'change' }],
  checkDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  bloodPressureSystolic: [
    { required: true, message: '请输入收缩压' },
    { type: 'number', min: 70, max: 200, message: '收缩压应在70-200mmHg之间' }
  ],
  bloodPressureDiastolic: [
    { required: true, message: '请输入舒张压' },
    { type: 'number', min: 40, max: 120, message: '舒张压应在40-120mmHg之间' }
  ],
  bloodSugar: [
    {required: true, message: '请输入血糖'},
    {type: 'number', min: 40, max: 200, message: '血糖应在40-200之间'}
  ]
})

// 状态标签转换方法
const getSleepQualityTag = (val: number) => {
  const map = ['success', 'info', 'warning', 'danger']
  return map[val - 1] || ''
}

const getSleepQualityText = (val: number) => {
  const map = ['优', '良', '中', '差']
  return map[val - 1] || '未知'
}

const getMoodTag = (val: number) => {
  const map = ['success', 'info', 'warning', 'danger']
  return map[val - 1] || ''
}

const getMoodText = (val: number) => {
  const map = ['愉快', '平静', '焦虑', '抑郁']
  return map[val - 1] || '未知'
}

// 打开对话框
const openDialog = (row?: HealthLog) => {
  if (row) {
    Object.assign(form, row)
  } else {
    resetForm()
    if (oneSelf.value){
      form.userId = oneSelfId.value
    }
  }
  dialogVisible.value = true
  getUserListByTypeFun()
}
const getUserListByTypeFun = () =>{
  const userQuery = {
    size: 1000,
    userType: 1
  }
  getUserListByType(userQuery).then(res=>{
    console.log(res)
    userList.value=res.records
  })

}
// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  form.id = undefined
  form.userId = undefined
  form.checkDate = new Date().toISOString().split('T')[0]
  form.temperature = 36.5
  form.systolicPressure = 120
  form.diastolicPressure = 80
  form.heartRate = 75
  form.weight = 60
  form.sleepQuality = 1
  form.sleepDuration = 7.5
  form.mood = 2
  form.note = ''
}

// 获取健康日志列表
const fetchHealthLogs = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }

    const res = await get('/health-log/page', params)
    healthLogList.value = res.records
    total.value = res.total
  } catch (error) {
    console.log(error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitLoading.value = true

    const api = form.id ? put : post
    const url = form.id ? `/health-log/${form.id}` : '/health-log'
    console.log(form)
    await api(url, form)
    ElMessage.success(form.id ? '更新成功' : '添加成功')
    dialogVisible.value = false
    fetchHealthLogs()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 删除记录
const handleDelete = async (row: HealthLog) => {
  try {
    await ElMessageBox.confirm('确定删除该记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await del(`/health-log/${row.id}`)
    ElMessage.success('删除成功')
    fetchHealthLogs()
  } catch (error) {
    console.log('取消删除')
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchHealthLogs()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  queryParams.startDate = ''
  queryParams.endDate = ''
  fetchHealthLogs()
}

// 分页处理
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  fetchHealthLogs()
}

const handleCurrentChange = (num: number) => {
  queryParams.pageNum = num
  fetchHealthLogs()
}

const oneSelf = ref(false)
const oneSelfId = ref()
const checkUserAuth = () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  if(user.userAuth === '' || user.userAuth === null){
    oneSelf.value = true
    oneSelfId.value = user.id
  }else{
    oneSelf.value = false
    oneSelfId.value = ''
  }
}
// 初始化加载
onMounted(() => {
  fetchHealthLogs()
  getUserListByTypeFun()
  checkUserAuth()

})
</script>
